<?php

namespace Morrow;

class PageController extends DefaultController {
	public function run() {
		$this->form->loadDef(
			array('myform' => array(

		            "email" => array(
		            	"type" => "text",
		            	"required" => true,
		            	"label" => "email :",
		            	"checktype" => "Email"    
	            	),

	            	"password" => array(
		            	"required" => true,
		            	"type" => "text",
		            	"displaytype" => "password",
		            	"checktype" => "password",
		            	"label" => "password :",


	            	),
            	)
            )
        );
		
		if($this->session->get("uid")){
			$this -> url -> redirect('home');
		}

		$this->form->setInput($this->input->get()); 

		if($this -> form -> isSubmitted('myform')) {
    			$valid = $this -> form -> validate('myform');

    			

            	$this->view->setContent($this->form->getErrors('myform'), "error");

    				if ($valid) {
        		        $formdata = $this -> form -> getValues('myform');

                        $this->load('Db', $this->config->get('db'));
                        //var_dump($formdata);

						$sql = $this->db->result('
							SELECT password
							FROM users
							WHERE email = ?'
							, $formdata['email']);

						if(count($sql["RESULT"])==0){

							$this->form->setError('myform','password',$this->language->_('帐号或密码错误') );
						}

						elseif(md5($formdata["password"]) == $sql["RESULT"][0]["password"]){
							// get uid and set session
							$sql_uid = $this->db->result('
								SELECT uid
								FROM users
								WHERE email = ?'
								, $formdata['email']);

							$uid = $sql_uid["RESULT"][0]["uid"];
							$this->session->set("uid", $uid);
							$this->session->set("email", $formdata['email']);
							//var_dump($this->session->get("email"));

							$this->session->set('messenger','login1');
							$this -> url -> redirect('user');
							
						}
						else{
							 $this->form->setError('myform','password',$this->language->_('帐号或密码错误') );
						}
        				//$this -> url -> redirect('home');
    				} 
    				else {
    				}
		}

	}
}
